package com.novax.ex.activity.provider.controller;

import com.alibaba.fastjson.JSON;
import com.novax.ex.activity.infrastructure.entity.MallOrderWinner;
import com.novax.ex.activity.infrastructure.entity.MallPrize;
import com.novax.ex.activity.infrastructure.entity.MallPrizeOrder;
import com.novax.ex.activity.open.api.MallPrizeOrderApi;
import com.novax.ex.activity.open.model.query.MallPrizeOrderQuery;
import com.novax.ex.activity.open.model.request.MallPrizeOrderRequest;
import com.novax.ex.activity.open.model.response.MallPrizeOrderResponse;
import com.novax.ex.activity.provider.api.UserAssetApi;
import com.novax.ex.activity.provider.api.model.UserAsset;
import com.novax.ex.activity.provider.handler.provider.MallOrderProvider;
import com.novax.ex.activity.provider.service.*;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.CopyUtils;
import com.novax.ex.common.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description
 * @Author zhaolei
 * @Date 2/22/23 8:47 PM
 * @Version 1.0
 */
@Slf4j
@RestController
public class MallPrizeOrderController extends BaseActivityController implements MallPrizeOrderApi {
    @Resource
    private UserAssetApi userAssetApi;
    @Resource
    private MallPrizeOrderService mallPrizeOrderService;
    @Resource
    private MallProductBannerService mallProductBannerService;
    @Resource
    private MallOrderProvider mallOrderProvider;
    @Resource
    private MallOrderWinnerService mallOrderWinnerService;
    @Resource
    private MallPrizeService mallPrizeService;

    @Override
    public ReturnResult<?> buy(Long userId, String language, MallPrizeOrderRequest orderRequest) {
        ReturnResult<MallPrizeOrder> result = mallPrizeOrderService.buy(userId, language, orderRequest);
        if(result.isSuccess()) {
            MallPrizeOrder order = result.getData();
            //发送购买成功消息
            if (result.isSuccess()) {
                mallOrderProvider.sendBuy(JSON.toJSONString(order));
            }
            //查询本次的奖品池记录的标记，并返回
            MallPrize prize = mallPrizeService.find(orderRequest.getMallPrizeId());
            Map<String, Integer> map = new HashMap<>();
            map.put("status", prize.getStatus());
            return ReturnResult.result(map, result.getCode(), result.getMsg());
        }else{
            return result;
        }
    }

    @Override
    public ReturnResult<BigDecimal> asset(Long userId, String language, String currency) {
        //查询现货系统的余额
        ReturnResult<UserAsset> assetReturnResult = userAssetApi.findAsset(userId, currency);
        if (Objects.nonNull(assetReturnResult) && assetReturnResult.isSuccess()) {
            UserAsset asset = assetReturnResult.getData();
            if (Objects.nonNull(asset)) {
                return ReturnResult.success(asset.getAvailable().setScale(8, BigDecimal.ROUND_DOWN));
            }
        }
        return ReturnResult.success(BigDecimal.ZERO);
    }

    @Override
    public ReturnResult<PageUtil<MallPrizeOrderResponse>> list(Long userId, String language, MallPrizeOrderQuery query) {
        return mallPrizeOrderService.list(userId, language, query);
    }

    @Override
    public ReturnResult<MallPrizeOrderResponse> unclaimed(Long userId, String language) {
        MallOrderWinner mallOrderWinner = mallOrderWinnerService.unclaimed(userId);
        if(Objects.nonNull(mallOrderWinner)) {
            MallPrizeOrder mallPrizeOrder = mallPrizeOrderService.find(mallOrderWinner.getMallPrizeOrderId());
            if (Objects.nonNull(mallPrizeOrder)) {
                MallPrizeOrderResponse response = CopyUtils.copyObject(mallPrizeOrder, MallPrizeOrderResponse.class);
                //查询主图
                String img = mallProductBannerService.getByMainImg(mallPrizeOrder.getMallProductId());
                response.setImg(img);
                //查询提示商品购买成功多语言
                String msg = getInternational(language, InternationalCode.USER_MALL_ORDER_BUY_SUCCESS);
                setOrderResponse(response,msg,mallPrizeOrder,language);
                return ReturnResult.success(response);
            }
        }
        return ReturnResult.success();
    }
    private String getShare(String language,String unit,String productName){
        String share = getInternational(language, InternationalCode.USER_MALL_ORDER_WINNER_SHARE);
        if(StringUtils.isNotBlank(share)) {
            if (StringUtils.isNotBlank(unit)) {
                share = share.replace("{0}", unit);
            }
            if (StringUtils.isNotBlank(productName)) {
                share = share.replace("{1}", productName);
            }
        }else{
            share = "";
        }
        return share;
    }

    @Override
    public ReturnResult<MallPrizeOrderResponse> getWinnerNew(Long userId, String language) {
        MallOrderWinner mallOrderWinner = mallOrderWinnerService.getWinnerNew(userId);
        if(Objects.nonNull(mallOrderWinner) && mallOrderWinner.getReadStatus().intValue() == 0) {
            MallPrizeOrder mallPrizeOrder = mallPrizeOrderService.find(mallOrderWinner.getMallPrizeOrderId());
            if (Objects.nonNull(mallPrizeOrder)) {
                MallPrizeOrderResponse response = new MallPrizeOrderResponse(); //CopyUtils.copyObject(mallPrizeOrder, MallPrizeOrderResponse.class);
                response.setId(mallOrderWinner.getId());
                //查询主图
                String img = mallProductBannerService.getByMainImg(mallPrizeOrder.getMallProductId());
                response.setImg(img);
                response.setSnapshotTitle(mallPrizeOrder.getSnapshotTitle());
                //查询提示商品购买成功多语言
                String msg = getInternational(language, InternationalCode.USER_MALL_ORDER_SEND_SUCCESS);
                setOrderResponse(response,msg,mallPrizeOrder,language);
                return ReturnResult.success(response);
            }
        }
        return ReturnResult.success();
    }

    private void setOrderResponse(MallPrizeOrderResponse response,String msg,MallPrizeOrder mallPrizeOrder,String language){
        response.setSnapshotTitle(response.getSnapshotTitle()+ " " + msg);
        String unit = mallPrizeOrder.getMinPrice().stripTrailingZeros().toPlainString()+mallPrizeOrder.getCurrency().toUpperCase();
        response.setShare(getShare(language,unit,mallPrizeOrder.getSnapshotTitle()));
        List<String> highlighting = new ArrayList<>();
        highlighting.add(unit);
        highlighting.add(mallPrizeOrder.getSnapshotTitle());
        response.setHighlighting(highlighting);
    }

    @Override
    public ReturnResult<?> setWinnerNewTag(Long userId, String language, Long id) {
        mallOrderWinnerService.setWinnerNewTag(id);
        return ReturnResult.success();
    }
}
